<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px" :label-position="labelPosition">
      <el-form-item label="客户" prop="khmc">
        <el-select
            v-model="queryParams.khmc"
            placeholder="请输入客户"
            clearable
            @change="changeSelectClient"
            filterable
            :loading="selectClient3Loading"
        >
            <el-option
                v-for="(item, index) in cilentList"
                :key="index"
                :label="item.khmc"
                :value="item.khmc"
            />
        </el-select>
      </el-form-item>
       <el-form-item label="截止日期" prop="rqid">
          <el-date-picker
            value-format="yyyy-MM-dd"
            default-value
            v-model="queryParams.rqid"
            type="date"
            placeholder="请输入截止日期"
            @change="changeDate">
          </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="search">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="customerCategoryList"
    >
      <af-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="left">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="openDaysCategory(scope.row)"
            v-hasPermi="['zhcloud:sjfx:list']"
          >按日区分</el-button>
          <el-button
            size="mini"
            type="text"
            @click="openLeftGoods(scope.row)"
            v-hasPermi="['zhcloud:sjfx:list']"
          >剩余货物</el-button>
          <el-button
            size="mini"
            type="text"
            @click="openWarehousePositionCategory(scope.row)"
            v-hasPermi="['zhcloud:sjfx:list']"
          >按仓区分</el-button>
        </template>
      </af-table-column>
      <af-table-column label="客户" prop="khmc" />
      <af-table-column label="结存件数" prop="spjs2" />
      <af-table-column label="结存重量(吨)" prop="spsl2" />
      <af-table-column label="周转率" prop="zzlmz1" />
      <af-table-column label="月周转率" prop="zzlm1" />
      <af-table-column label="平均库存" prop="pjkcz2" />
      <af-table-column label="月平均库存" prop="pjkcm2" />
      <af-table-column label="月入仓件数" prop="spjsim2" />
      <af-table-column label="月入仓重量(吨)" prop="spslim2" />
      <af-table-column label="月出仓件数" prop="spjsom2" />
      <af-table-column label="月出仓重量(吨)" prop="spslom2" />
      <af-table-column label="寄存吨数" prop="spslj2" />
      <af-table-column label="质押吨数" prop="spslz2" />
    </el-table>
     <pagination
        v-show="total>0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="getList"
      />
      <el-form>
      <el-form-item label="结存天数">
        <el-radio v-model="queryChartParams.dayOrMonth" label="day" @change="changeDayOrMonth">按日</el-radio>
        <el-radio v-model="queryChartParams.dayOrMonth" label="month" @change="changeDayOrMonth">按月</el-radio>
      </el-form-item>
      <div id="customerCategoryChartId" :style="chartStyle" ></div>
      <div id="customerCategoryCircleChartId" :style="circleChartStyle" ></div>
    </el-form>
  </div>
 
</template>

<script>
import { getListCustomerCategory, getCustomerCategoryChart, getCustomerCategoryCircleChart } from "@/api/storage/dataAnalysis/customerCategory";
import { selectClient3 } from "@/api/storage/customer";
import { formatDate } from '@/utils'
import echarts from 'echarts';
import variables from '@/assets/styles/variables.scss'

export default {
  name: "CustomerCategory",
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      //对齐
      labelPosition: "right",
      //客户加载
      selectClient3Loading: true, 
      //列表加载
      loading:true,
      customerCategoryDate:'',
      // 查询参数
      queryParams: {
        khmc: "",
        rqid: ""
      },
      queryChartParams: {
        rqid:"",
        dayOrMonth:"day"
      },
       //图表属性
       chartStyle: {
        height:"500px",
        width:"800px",
        margin:"60px auto"
      },
      circleChartStyle: {
        height:"600px",
        width:"1000px",
        margin:"60px auto"
      },
      // 历史作业量列表
      customerCategoryList: [],
      //仓库列表
      cilentList:[],
      //页数
      pageSize: 10,
      //页码
      pageNum:1,
      // 总条数
      total: 0,
    };
  },
  beforeRouteEnter(to, from, next) {
    const params = to.params
    next(vm => {   
      if(Object.keys(params).length > 0) {
        if(to.params.refresh == true) {
          vm.getList()
        }
      }
    })
  },
  created() {
    const nowDate = formatDate(Date.now()).split(" ")[0]
    this.queryParams.rqid = nowDate
    this.queryChartParams.rqid = nowDate
    this.getCilent()
    this.getList()
  },
  mounted() {
    this.getChart()
    this.getCircleChart()
  },
  methods: {
    /**获取客户 */
    getCilent() {
      this.selectClient3Loading = true
      selectClient3({}).then(response => {
        this.cilentList = response.data
        this.selectClient3Loading = false
      });
    },
    /** 查询历史作业量列表 */
    getList() {
      this.loading = true
      getListCustomerCategory(this.queryParams, {pageNum:this.pageNum, pageSize:this.pageSize}).then(response => {
        this.customerCategoryList = response.rows;
        this.total = response.total;
        this.loading = false
      });
    },

     //圆柱图表
     getChart() {
      let chart = echarts.init(document.getElementById('customerCategoryChartId'))
      chart.showLoading({
        text:"",
        color:variables.defaultTheme,
        textCloor:variables.defaultTheme,
        spinnerRadius: 18,
        lineWidth: 2,
      })
      getCustomerCategoryChart(this.queryChartParams).then(response => {
        const data = response.data
        chart.hideLoading()
        this.initChart(data, chart)
      });
    },

     //饼状图表
     getCircleChart() {
      let chart = echarts.init(document.getElementById('customerCategoryCircleChartId'))
      chart.showLoading({
        text:"",
        color:"#192C59",
        textCloor:"#192C59",
        spinnerRadius: 18,
        lineWidth: 2,
      })
      getCustomerCategoryCircleChart({}).then(response => {
        const data = response.data
        chart.hideLoading()
        this.initCircleChart(data, chart)
      });
    },

    /**选择仓库 */
    changeWarehouse(id) {
      this.selectPositionQuery.spckid = id
      this.queryParams.ckcw = ""
      this.warehousePositionList = []
      if(this.selectPositionQuery.spckid) {
        this.getWarehousePosition()
      }
      this.getList()
      this.getChart()
      this.getCircleChart()
    },

    /**客户改变 */
    changeSelectClient() {
      this.getList()
      this.getChart()
      this.getCircleChart()
    },

    changeDayOrMonth() {
      this.getChart()
    },

    /**截至日期改变 */
    changeDate(data) {  
      this.queryChartParams.rqid = data
    },
    /**搜索 */
    search() {
      this.getList()
      this.getChart()
    },

    initChart(data, chart) {
      const data1 = data.sort((a,b) => b.ssrqid > a.ssrqid?-1:1)
      const xAxisName = data1.map(item => item.ssrqid)
      const weight = data1.map(item => item.spsl)
      let option = {
        title: {
          text: data1.length > 0?data1[0].aaa:"",
          left: "center",
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'cross' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: [{
          type: 'category',
          data: xAxisName,
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          name: '重量/吨',
        }],
        series: [{
          name: '重量',
          type: 'bar',
          barGap:'20%',
          barCategoryGap: '40%',
          barWidth: '60%',
          data: weight,
        }]
      }
      // 使用刚指定的配置项和数据显示图表。
      chart.setOption(option)
    },

    initCircleChart(data, chart) {
      const data1 = data.sort((a,b) => b.spsl - a.spsl)
      const legendData = data1.map(item => item.allName)
      const seriesData = data1.map(item => {
        return {
          name: item.allName,
          value: item.spsl
        }
      })

      let option =  {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}吨 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          type: 'scroll',
          right: 0,
          data: legendData,
          itemHeight: 20,
          itemGap: 10,
          textStyle: {
            fontSize: 16,
            fontWeight: 'bolder'
          }
        },
        series: [
          {
            name: '按客户区分',
            type: 'pie',
            radius: ['70%', '85%'],
            center: ['40%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center',
              formatter: '{b}\n\n{c}吨   {d}% '
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold',
                color: '#000'
              }
            },
            labelLine: {
              show: false
            },
            data: seriesData
          }
        ]
      }
      // 使用刚指定的配置项和数据显示图表。
      chart.setOption(option)
    },

    /**打开按日区分 */
    openDaysCategory(data) {
      this.$router.push({path:"/storage/dataAnalysis/customerCategory/customerCategoryDays", query:data})
    },

    /**打开剩余货物 */
    openLeftGoods(data) {
      this.$router.push({path:"/storage/dataAnalysis/customerCategory/customerCategoryLeftGoods", query:data})
    },

    /**打开按仓区分 */
    openWarehousePositionCategory(data) {
      this.$router.push({path:"/storage/dataAnalysis/customerCategory/customerCategoryWarehouse", query:data})
    },
    /**enter键触发 */
    enterClick(e) {
      this.getList()
      this.getChart()
      this.getCircleChart()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.reset()
      this.getCilent()
      this.getList()
      this.getChart()
      this.getCircleChart()
    },
    reset() {
      Object.assign(this.$data, this.$options.data())
    },
  }
};
</script>
